<?php
/**
 * 定时检测订单预警时间
 * Created by PhpStorm.
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/8/25
 * Time: 16:52
 */

namespace YMApi\Controller;
use Think\Controller;
use Think\Model;

class AlarmcheckController extends Controller
{
    public function check(){
        $this->del_log();               //删除日志
        $this->check_alarm();           //检查预警信息
        $this->check_alarm_type_4();    //插入自提单预警
        $this->check_alarm_type_wrong();    //插入问题单预警
        //$this->check_hook_goods();      //检查商品库存和登记数
        $this->operate_goods();         //检查运营平台数据
    }
    
    /**
     * [0979需求]库存系统-采购 缺货、滞销预警 触发;
     * http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/
     * 
     * 缺货滞销 重新触发 http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/all
     * 日销售量数据    http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/gds
     * 缺货数据    http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/gsw
     * 滞销数据    http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/unsold
     * @param string $trigger_date 触发日期，如2016-11-29;
     * @param string $type 触发类型，all全部触发; gds触发商品日销量数据生成; gsw触发生成数据缺货预警;unsold触发生成数据直销预警;
     * @author ^2_3^
     */
    public function shortagewarning_unsold_data() {
        $flag = false;
        $trigger_date = I("request.trigger_date", '', 'trim');
        if( empty($trigger_date) ) {
            $trigger_date = date("Y-m-d");
        }
        
        $trigger_time = strtotime( $trigger_date ) - 28800;
        $type = I("request.type", '', 'trim');
        if( empty($trigger_time) ) {
            exit('request error;');
        }
        
        $db_prefix = C('DB_PREFIX');
        if( $type == "all" ) {
            /// 删除数据
            $all_gds_del = "
                DELETE FROM {$db_prefix}goods_day_sales WHERE pay_date_time != 0;
            ";
            $all_gsw_del = "
                DELETE FROM {$db_prefix}goods_shortage_warning WHERE record_time != 0;
            ";
            $all_guw_sql = "
                DELETE FROM {$db_prefix}goods_unsold_warning WHERE record_time != 0;
            ";
            $all_gds_flag = M()->execute( $all_gds_del );
            $all_gsw_flag = M()->execute( $all_gsw_del );
            $all_guw_flag = M()->execute( $all_guw_sql );
            $all_del_flag = $all_gds_flag && $all_gsw_flag && $all_guw_flag;
            
            if( $all_del_flag || ($all_gds_flag === 0 && $all_gsw_flag === 0 && $all_guw_flag === 0) ) {
                /// 生成40天日销量数据
                $gds_end_time = $trigger_time;
                $gds_start_time = $gds_end_time - 3456000; //40*24*3600;
                $gds_flag = $this->goods_day_sales_data_add($gds_start_time, $gds_end_time);
    
                /// 缺货预警数据生成规则：当已经上架商品 库存量 < 预警库存量( 前30天销量/30 * 3 )时，列出缺货预警数据;
                $gsw_end_time = $trigger_time;
                $gsw_start_time = $gsw_end_time - 2592000; //30*24*3600;
                $gds_flag && $gsw_flag = $this->goods_shortage_warning_data_add($gsw_start_time, $gsw_end_time);
    
                /// 直销预警数据生成规则：当商品在连续前30天内，没有销量，列出滞销预警数据;
                $unsold_end_time = $trigger_time;
                $unsold_start_time = $unsold_end_time- 2592000; //30*24*3600;
                $gds_flag && $unsold_flag = $this->goods_unsold_data_add($unsold_start_time, $unsold_end_time);
    
                $gds_flag && $gsw_flag && $unsold_flag && $flag = true;
            }
    
        }else if( $type == "gds" ) {
            /// 生成最近10天商品日销量：先删除已有数据，再添加最新数据，保证数据准确; 16-11-29 -> 16-11-19
            $gds_end_time = $trigger_time;
            $gds_start_time = $gds_end_time - 864000; //10 * 24 * 3600;
            //-/ 删除
            $del_sql = "
            DELETE FROM {$db_prefix}goods_day_sales WHERE pay_date_time >= {$gds_start_time} AND pay_date_time <= {$gds_end_time}
            ";
            $del_flag = M()->execute( $del_sql );
            //-/ 添加
            $add_flag = $this->goods_day_sales_data_add($gds_start_time, $gds_end_time);
            $flag = $add_flag;
    
        }else if( $type == "gsw" ) {
            $gsw_end_time = $trigger_time;
            $gsw_start_time = $gsw_end_time - 2592000; //30*24*3600;
            $gsw_flag = $this->goods_shortage_warning_data_add($gsw_start_time, $gsw_end_time);
            $flag = $gsw_flag;
    
        }else if( $type == "unsold" ) {
            $unsold_end_time = $trigger_time;
            $unsold_start_time = $unsold_end_time- 2592000; //30*24*3600;
            $unsold_flag = $this->goods_unsold_data_add($unsold_start_time, $unsold_end_time);
            $flag = $unsold_flag;
        }
    
        $flag ? exit("1") : exit("0");
    }
    
    /**
     * 滞销预警商品_数据添加
     *
     * @param string $start_time 销售开始时间戳(零时区)，包含此时间戳数据;
     * @param string $end_time 销售结束日期时间戳(零时区)，不包含此时间戳数据;
     * @author ^2_3^
     */
    private function goods_unsold_data_add($start_time, $end_time) {
        $flag = false;
        if( empty($start_time) || empty($end_time) ) {
            return $flag;
        }

        $db_prefix = C('DB_PREFIX');
        $sql = "
        insert into {$db_prefix}goods_unsold_warning (
            goods_id,
            goods_sn,
            goods_name,
            cat_name,
            sum_practical_num,
            brand_name,
            sum_goods_number,
            begin_time,
            end_time,
            record_time
        )
        SELECT * FROM
        (
            SELECT
                tmp_save.goods_id,
                tmp_save.goods_sn,
                tmp_save.goods_name,
                cat_name,
                IFNULL(sum_practical_num, 0) AS sum_practical_num,
                brand_name,
                sum_goods_number,
                '{$start_time}' AS begin_time,
                '{$end_time}' AS end_time,
                (UNIX_TIMESTAMP()-28800) AS record_time
            FROM
            (
            
                -- 商品库存
                SELECT
                    g.goods_id,
                    g.goods_sn,
                    g.goods_name,
                    SUM(gs.practical_num) AS sum_practical_num,
                    c.cat_name,
                    b.brand_name
                FROM {$db_prefix}goods g
                LEFT JOIN {$db_prefix}goods_storage gs ON g.goods_id = gs.goods_id
                LEFT JOIN {$db_prefix}category c ON g.cat_id = c.cat_id
                LEFT JOIN {$db_prefix}brand b ON g.brand_id = b.brand_id
                WHERE g.is_on_sale = 1 AND g.is_delete = 0
                GROUP BY g.goods_id
                
            ) tmp_save
            LEFT JOIN
            (
            
                -- 商品日销量
                SELECT
                    gds.goods_id,
                    gds.goods_sn,
                    gds.goods_name,
                    SUM(gds.sum_goods_number) AS sum_goods_number
                FROM {$db_prefix}goods g
                LEFT JOIN {$db_prefix}goods_day_sales gds ON gds.goods_id = g.goods_id
                WHERE gds.pay_date_time >= {$start_time}
                AND gds.pay_date_time <= {$end_time}
                AND g.is_on_sale = 1
                AND g.is_delete = 0
                GROUP BY gds.goods_id
                
            ) tmp_sales ON tmp_sales.goods_id = tmp_save.goods_id
        ) tmp WHERE sum_goods_number IS NULL
        ";
        
        $flag = M()->execute( $sql );
//         $this->w_log( "滞销预警商品_数据添加 {$sql}" );
    
        return $flag;
    }
    
    /**
     * 缺货预警_数据添加
     *
     * @param string $start_time 销售开始时间戳(零时区)，包含此时间戳数据;
     * @param string $end_time 销售结束日期时间戳(零时区)，不包含此时间戳数据;
     * @author ^2_3^
     */
    private function goods_shortage_warning_data_add($start_time, $end_time) {
        $flag = false;
        if( empty($start_time) || empty($end_time) ) {
            return $flag;
        }
    
        $db_prefix = C('DB_PREFIX');
        $sql = "
        -- 缺货预警表_数据添加
        insert into {$db_prefix}goods_shortage_warning(
            goods_id,
            goods_sn,
            goods_name,
            sum_practical_num,
            sum_goods_number,
            begin_time,
            end_time,
            daily_sales_num,
            warning_num,
            record_time
        )
        SELECT
            goods_id,
            goods_sn,
            goods_name,
            sum_practical_num,
            sum_goods_number,
            '{$start_time}' AS begin_time,
            '{$end_time}' AS end_time,
            (sum_goods_number/30) AS daily_sales_num,
            (sum_goods_number/10) AS warning_num,
            (UNIX_TIMESTAMP()-28800) AS record_time
        FROM
        (
            -- 商品所选时段库存销量_数据
            SELECT
                tmp_g.goods_id,
                tmp_g.goods_sn,
                tmp_g.goods_name,
                sum_practical_num,
                sum_goods_number
            FROM
            (
            
                -- 商品库存
                SELECT
                    g.goods_id,
                    g.goods_sn,
                    g.goods_name,
                    SUM(gs.practical_num) AS sum_practical_num
                FROM {$db_prefix}goods g
                LEFT JOIN {$db_prefix}goods_storage gs ON g.goods_id = gs.goods_id
                WHERE g.is_on_sale = 1 AND g.is_delete = 0
                GROUP BY g.goods_id
                
            ) tmp_g
            LEFT JOIN
            (
            
                -- 所选时段销售数量
                SELECT
                    goods_id,
                    goods_sn,
                    goods_name,
                    SUM(sum_goods_number) AS sum_goods_number
                FROM {$db_prefix}goods_day_sales gds
                WHERE gds.pay_date_time >= {$start_time} AND gds.pay_date_time < {$end_time}
                GROUP BY gds.goods_id
                
            ) tmp_s ON tmp_g.goods_id = tmp_s.goods_id
            ORDER BY goods_id
    
        ) tmp_result WHERE sum_practical_num < ((sum_goods_number/30) * 3)
        ";
        
        $flag = M()->execute( $sql );
//         $this->w_log( "缺货预警_数据添加 {$sql}" );
    
        return $flag;
    }
    
    /**
     * 商品日销售表_数据添加
     *
     * @param string $pay_start_time 销售开始时间戳(零时区)，包括此时间戳;
     * @param string $pay_end_time 销售结束时间戳(零时区)，不包括此时间戳;
     * @author ^2_3^
     */
    private function goods_day_sales_data_add($pay_start_time, $pay_end_time) {
        $flag = false;
    
        if( empty($pay_start_time) || empty($pay_end_time)  ) {
            return $flag;
        }
    
        $db_prefix = C('DB_PREFIX');
        $sql = "
        insert into {$db_prefix}goods_day_sales(goods_id, goods_sn, goods_name, sum_goods_number, pay_date, pay_date_time)
        select * from
        (
            -- 商品日销售表_数据
            SELECT
                goods_id,
                goods_sn,
                goods_name,
                SUM(goods_number) AS sum_goods_number,
                pay_date,
                pay_date_time
            FROM
            (
                SELECT
                    oi.order_id,
                    oi.order_sn,
                    oi.pay_time,
                    FROM_UNIXTIME(oi.pay_time+28800, '%Y-%m-%d') AS pay_date,
                    UNIX_TIMESTAMP(FROM_UNIXTIME(oi.pay_time+28800, '%Y-%m-%d')) AS pay_date_time,
                    og.goods_id,
                    og.goods_sn,
                    og.goods_name,
                    og.goods_number
                FROM {$db_prefix}order_info oi
                LEFT JOIN {$db_prefix}order_goods og ON oi.order_id = og.order_id
                LEFT JOIN {$db_prefix}users u ON oi.user_id = u.user_id 
                WHERE pay_time >= {$pay_start_time}
                AND pay_time < {$pay_end_time}
                AND u.user_name NOT LIKE 'wx_196%' 
                AND oi.order_status IN (1, 5)
                AND oi.pay_status IN (2, 3)
                AND oi.shipping_status = 2
            ) sell_tmp
            GROUP BY pay_date, goods_id
        ) tmp
        ";
        $flag = M()->execute( $sql );
//         $this->w_log( "商品日销售表_数据添加 {$sql}" );
    
        return $flag;
    }
    
    /**
     * 删除日志
     */
    public function del_log(){

        M("alarm_log2")->where('type NOT IN (5)')->delete();
        M("alarm_log2")->where('type = 4 AND state = 1')->delete();

    }


    /**
     *检查库存并检查预约发送信息
     */
    private function check_hook_goods(){

        $booking_goods_array = M("booking_goods")->field("rec_id,tel,goods_id,user_id,goods_name")->where(array("is_dispose"=>0))->select();
        $goods_array = $booking_goods_array['goods_id'];
        $goods_array = array_unique($goods_array);
        if(count($goods_array)>0){
            foreach ($goods_array as $key=>$goods_id){
                $practical_num = M("goods_storage")->where(array("goods_id"=>$goods_id))->getField("practical_num");
                if($practical_num>0){

                    $this->handle_booking($booking_goods_array[$key]['rec_id'],$booking_goods_array[$key]['tel'],$booking_goods_array[$key]['user_id'],$booking_goods_array[$key]['goods_name']);
                }
            }
        }
    }

    /**
     * 修改记录并发送信息
     * @param $rec_id
     * @param $tel
     */
    private function handle_booking($rec_id, $tel,$user_id,$goods_name){
        $data['is_dispose'] = 1;
        $data['dispose_user'] = "系统";
        $data['dispose_time'] = gmtime();
        $data['dispose_note'] = "检测到仓储不为空，自动发送信息给用户";
        M("booking_goods")->where('rec_id='.$rec_id)->save($data);
        $remark['goods_name'] = $goods_name;
        //发送信息给用户
        A("Smsapi")->send_message_api("goods_arrive",$tel,$tel,0,0,0,$user_id,$remark);

    }

    /**
     *检查预警信息
     */
    private function check_alarm(){
        $item_list = M("alarm")->find();

        $no_ready = $item_list['no_ready'];                   //未配货预警时间
        $no_distribution = $item_list['no_distribution'];     //未配送预警时间
        $distribution = $item_list['distribution'];           //未送达预警时间
        $since = $item_list['since'];                         //自提预警时间
        $alarm_interval = $item_list['alarm_interval'];       //预警时间间隔
        $since_cancel = $item_list['since_cancel'];           //自提订单取消时间
        $alarm_presell=$item_list['alarm_presell'];//预售商品缺货预警设置

        $order_info = M('order_info');



        if($no_distribution>0){
            //已开启未配送提醒   同时提醒未出仓
            $where= "order_status !=2 and  shipping_status = 5  and outgo = 0 and shipping_id = 3 and sorting_id !=0";   //已发货的送货上门订单，超出时间范围
            $order_sn = $order_info->where($where)->getField('order_sn',true);

            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where('type =8 and order_sn='.$value)->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,8);
                        }
                    }else{
                        $this->w_alarm_log($values,8);
                    }
                }
            }
        }
        if($no_distribution>0){
            //已开启未配送提醒   同时提醒未回仓
            $where= "order_status !=2 and outgo = 2 and shipping_id = 3";   //已发货的送货上门订单，超出时间范围
            $order_sn = $order_info->where($where)->getField('order_sn',true);

            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where('type =9 and order_sn='.$value)->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,9);
                        }
                    }else{
                        $this->w_alarm_log($values,9);
                    }
                }
            }
        }

        if($no_ready>0){
            //已开启未配货提醒
            $c_time = time()+$no_ready;       //预推时间到
            //已支付且未确认的送货上门订单
            $where= "pay_status in (2,3) and order_status <>2 and shipping_status IN (0,3) and shipping_id = 3 and best_time_start > 0  and best_time_start <".$c_time;
            $order_sn = $order_info->where($where)->getField('order_sn',true);
            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where('type = 1 and order_sn='.$value)->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,1);
                        }
                    }else{
                        $this->w_alarm_log($values,1);
                    }
                }
            }
        }


        if($no_distribution>0){
            //已开启未配送提醒
            //dump(gmtime());
            //dump($no_distribution);
            $c_time = gmtime()-$no_distribution;
            //已确认且未发货的送货上门订单
//            $where= "order_info.outgo = 1 and order_info.shipping_status = 5 and order_info.sorting_id <> 0 and order_info.order_status not in (0,2,3,4)
//            and order_info.shipping_id = 3 and deliver_order.add_time <".$c_time ." and order_info.order_id = deliver_order.order_id";  //根据配货时间开始算
//
//            $order_sn =M()->table(array('sdx_order_info'=>'order_info','sdx_warehouse_deliver_order'=>'deliver_order'))
//                ->field('order_info.order_sn')->where($where)->order('id desc')->select();
            $order_sn = M('order_info')->where('outgo = 1 and shipping_status = 5 and sorting_id <>0 and order_status <> 2 and shipping_id = 3 and pay_status in(2,3) and sorting_time<'.$c_time)->getField('order_sn',true);
            //dump(M('order_info')->getlastsql());
            //($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where('type = 2 and order_sn='.$value)->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){

                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,2);
                        }
                    }else{
                        $this->w_alarm_log($values,2);
                    }
                }
            }
        }

        if($distribution>0){
            //已开启未送达提醒
            $c_time = gmtime()-$distribution;
            //已发货的送货上门订单
            $where= "shipping_status = 1  and order_status =5 and shipping_id = 3 and shipping_time <> 0 and shipping_time <".$c_time;   //已发货的送货上门订单，超出时间范围
            $order_sn = $order_info->where($where)->getField('order_sn',true);

            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where('type =3 and order_sn='.$value)->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,3);
                        }
                    }else{
                        $this->w_alarm_log($values,3);
                    }
                }
            }
        }


        if($since>0){
            //自提预警时间111
            $h = intval(floor($since/3600));
            $m = ($since%3600)/60;
            //if(time()>strtotime(date("y-m-d",time())." ".$h.":".$m.":00")){
            $set_time = $h.":".$m;
            if(date("H:i",time())==$set_time){
                //已达到发送时间

                //已确认且未确认收货的上门自提订单,,,查询今天的数据
                $date_1 = strtotime(date("y-m-d",$this->gmtime())." 00:00:00");
                $date_2 = strtotime(date("y-m-d",$this->gmtime())." 23:59:59");
                $where= "shipping_status <> 2 and order_status = 5 and shipping_id = 2 and (pay_time  between ".$date_1." and ".$date_2.")";
                $order_sn = $order_info->where($where)->select();

//                dump($order_sn);
//                dump($order_info->getlastsql());
//
//                exit();
                if($order_sn){
                    foreach ($order_sn as $key=>$value){
                        $up_trigger_time = M("alarm_log2")->where('type = 4 and order_sn='.$value['order_sn'])->order('id desc')->getField('trigger_time');
                        if($up_trigger_time){
                            if((time()-$up_trigger_time)>86400){    //一天提醒一次
                                $this->w_alarm_log($value['order_sn'],4);
                                A("Smsapi")->send_message_api("order_remind",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                            }
                        }else{
                            $this->w_alarm_log($value['order_sn'],4);
                            A("Smsapi")->send_message_api("order_remind",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                        }
                    }
                }
                //已确认且未确认收货的上门自提订单,,,查询昨天的数
                $date_1 = strtotime(date("Y-m-d",$this->gmtime()-86400)." 00:00:00");
                $date_2 = strtotime(date("Y-m-d",$this->gmtime()-86400)." 23:59:59");

                $where= "shipping_status <> 2 and order_status = 5 and shipping_id = 2 and (pay_time  between ".$date_1." and ".$date_2.")";
                $order_sn = M('order_info')->where($where)->select();
                if($order_sn){
                    foreach ($order_sn as $key=>$value){
                        $up_trigger_time = M("alarm_log2")->where('type = 4 and order_sn='.$value['order_sn'])->order('id desc')->getField('trigger_time');
                        if($up_trigger_time){
                            if((time()-$up_trigger_time)>86400){
                                $this->w_alarm_log($value['order_sn'],4);
                                A("Smsapi")->send_message_api("order_warning",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                            }
                        }else{
                            $this->w_alarm_log($value['order_sn'],4);

                            A("Smsapi")->send_message_api("order_warning",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                        }
                    }
                }
            }

            //取消超时订单
            $h = intval(floor($since_cancel/3600));
            $m = ($since_cancel%3600)/60;
            $set_time = $h.":".$m;
            if(date("H:m",time())==$set_time){
                //取消前天的订单
                $date_2 = strtotime(date("Y-m-d",$this->gmtime()-172800)." 23:59:59");
                $where= "order_status in(5,6) and shipping_status = 1 and shipping_id = 2 and pay_time  <".$date_2;
                $order_sn = M('order_info')->where($where)->select();
//                dump(M('order_info')->getlastsql());
//                dump($order_sn);
                if($order_sn){
                    foreach ($order_sn as $key=>$value){
                        $this->w_alarm_log($value['order_sn'],5);
                        //取消订单
                        M('order_info')->where(array("order_id"=>$value['order_id']))->setField('order_status',2);
                        //写入订单取消记录
                        $data['order_id'] = $value['order_id'];
                        $data['action_user'] = '系统';
                        $data['order_status'] = 2;
                        $data['shipping_status'] = $value['shipping_status'];
                        $data['pay_status'] = $value['pay_status'];
                        $data['log_time'] = gmtime();
                        $data['action_note'] = '系统定时任务自动取消';

                        M('order_action')->add($data);

                        //dump("已取消订单:".$value['order_sn']);
                        A("Smsapi")->send_message_api("order_cancel",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");

                    }
                }
            }


            //清空未处理订单的记录
            if(date("H:m",time())=="23:55"){
                M('alarm_log2')->where(array("type"=>5,"state"=>0))->delete();
            }

        }

        if($alarm_presell>0){
            //
            $h = intval(floor($alarm_presell/3600));
            $m = ($alarm_presell%3600)/60;
            if($m==0){
                $m='00';
            }
            $time=time();
            $set_date_ymd=date('Y-m-d',$time);
            $set_time = $set_date_ymd.$h.":".$m;
            $set_time = strtotime($set_time);
            if($time >= $set_time){
                $is_presell_sql='SELECT * FROM(SELECT oi.order_id,oi.order_sn FROM '.C('DB_PREFIX').'order_info as oi'.
                    ' LEFT JOIN  '.C('DB_PREFIX').'order_goods as og ON og.order_id=oi.order_id'.
                    ' WHERE og.is_presell=1 AND og.buckle_inventory=0 AND (oi.pay_status IN (2,3)) AND oi.pay_status!=4 AND oi.shipping_status =0'.
                    " AND (oi.order_status NOT IN (0,2,3,4)) AND oi.best_time < UNIX_TIMESTAMP(date_format(now(), '%Y-%m-%d 23:59:59'))".
                    ' ) as t'.
                    ' GROUP BY order_id';
                $order_info=M()->query($is_presell_sql);
                if($order_info){
                    foreach ($order_info as $key=>$val){
                        if($this->check_yujing_distinct($val['order_sn'],7)){
                            $values['order_sn'] = $val['order_sn'];
                            $this->w_alarm_log($values,7);
                        }
                    }
                }
            }
        }
    }

    /**
     * 插入问题单预警日志
     * Created by Jerry
     */
    private function check_alarm_type_wrong()
    {
        $sql = "SELECT o.order_sn, a.action_type FROM sdx_order_action as a 
                LEFT JOIN sdx_order_goods AS g ON a.order_id = g.order_id 
                LEFT JOIN sdx_order_info AS o ON o.order_id = a.order_id
                LEFT JOIN sdx_alarm_log2 as al ON al.order_sn = o.order_sn
                WHERE 
                a.action_type = 6
                AND 
                o.shipping_status != 2
                AND
                al.order_sn IS NULL
                AND 
                o.shipping_status != 3
                AND 
                o.order_status != 2
                GROUP BY o.order_sn";

        $model = M();

        $rs = $model->query($sql);

        foreach ($rs  as $k => $v){
            $this->w_alarm_log($v, $v['action_type']);
        }
    }

    /**
     * 自提单预警插入
     * Created by Jerry
     */
    private function check_alarm_type_4()
    {
        $sql = "SELECT o.order_sn, 4 as type FROM sdx_order_info as o 
                LEFT JOIN
                sdx_alarm_log2 AS a
                ON
                (o.order_sn = a.order_sn)
                WHERE
                a.order_sn IS NULL
                AND 
                o.`shipping_id` = 2
                AND
                o.order_status != 2
                AND 
                o.pay_status = 2
                AND
                (
                o.shipping_status = 1
                OR 
                o.shipping_status = 0
                )
                GROUP BY o.order_sn";

        $model = M();

        $rs = $model->query($sql);

        foreach ($rs  as $k => $v){
            $this->w_alarm_log($v, $v['type']);
        }
    }

    /*
     * 根据预警日志去重
     * */
    private function check_yujing_distinct($order_sn,$type){
        $id=M('alarm_log2')->where(array('order_sn'=>$order_sn,'type'=>$type,'state'=>0))->getField('id');
        if($id>0){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 写入警告记录
     * @param $order_sn
     * @param $type
     */
    private function w_alarm_log($value, $type){
        $in_data['order_sn'] = $value['order_sn'];
        $in_data['type'] = $type;
        $in_data['trigger_time'] = time();
        $in_data['state'] = 0;
        M('alarm_log2')->add($in_data);
    }


    private function w_operate_log($goods_sn,$goods_id,$goods_name,$type){
        $in_data['goods_sn'] = $goods_sn;
        $in_data['goods_id'] = $goods_id;
        $in_data['goods_name'] = $goods_name;
        $in_data['type'] = $type;
        M('operate_log')->add($in_data);
    }


    private function operate_goods(){

        $model = M();

        //未上架有库存
//        $goods_list = M("goods")->where('is_on_sale = 0')->field('goods_id,goods_sn,goods_name')->select();
//        foreach ($goods_list as $key=>$value){
//            $practical_num = M("goods_storage")->where('goods_id = '.$value['goods_id'])->SUM('practical_num');
//            //dump($practical_num."---".M("goods_storage")->getlastsql());
//            if($practical_num>0){
//                $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],1);
//            }
//        }

        $sql = "SELECT
	gd.goods_id,gd.goods_sn,gd.goods_name
FROM
	sdx_goods AS gd
WHERE
	(
		SELECT
			SUM(gs.practical_num)
		FROM
			sdx_goods_storage AS gs
		WHERE
			gd.goods_id = gs.goods_id
	) > 0
AND gd.is_on_sale = 0 AND gd.is_delete = 0";

        $goods_list = $model->query($sql);


        M("operate_log")->where('type = 1')->delete();

        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],1);
        }




        //无库存已上架

        $sql = "SELECT
	gd.goods_id,gd.goods_sn,gd.goods_name
FROM
	sdx_goods AS gd
WHERE
	(
		SELECT
			SUM(gs.practical_num)
		FROM
			sdx_goods_storage AS gs
		WHERE
			gd.goods_id = gs.goods_id
	) = 0
AND gd.is_on_sale = 1 AND gd.is_delete = 0";

        $goods_list = $model->query($sql);
        M("operate_log")->where('type = 2')->delete();
        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],2);
        }

//
//
//
//
//        $goods_list = M("goods")->where('is_on_sale = 1')->field('goods_id,goods_sn,goods_name')->select();
//        foreach ($goods_list as $key=>$value){
//            $practical_num = M("goods_storage")->where('goods_id = '.$value['goods_id'])->SUM('practical_num');
//            if($practical_num==0){
//                //dump($practical_num."---".M("goods_storage")->getlastsql());
//                $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],2);
//            }
//        }
        //无图片已上架
        $goods_list = M("goods")->where('is_on_sale = 1 AND goods_thumb =""  AND is_delete = 0')->field('goods_id,goods_sn,goods_name')->select();
        //dump($goods_list."---".M("goods")->getlastsql());
        M("operate_log")->where('type =3')->delete();
        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],3);
        }

//        有图片未上架
		$goods_list = M("goods")->where('is_on_sale = 0 AND goods_thumb !=""  AND is_delete = 0')->field('goods_id,goods_sn,goods_name')->select();
		//dump($goods_list."---".M("goods")->getlastsql());
		M("operate_log")->where('type = 10')->delete();
		foreach ($goods_list as $key=>$value){
			$this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],10);
		}
    }
}